package com.cmos.um.exception;

import com.cmos.um.utils.Result;
import com.cmos.um.utils.ResultUtil;
import com.cmos.um.utils.RetMap;
import com.cmos.um.utils.exception.ExceptionEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

/**
 * 统一异常处理
 */
@ControllerAdvice
@ResponseBody
public class CommonExceptionAdvice {
    private static Logger logger = LoggerFactory.getLogger(CommonExceptionAdvice.class);

    /**
     * 400 - Bad Request
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public RetMap handleMissingServletRequestParameterException(HttpMessageNotReadableException e) {
        logger.error("json格式不正确", e);
        return new RetMap("0", "json格式不正确");
    }

    /**
     * 操作数据库出现异常:名称重复，外键关联
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(DataIntegrityViolationException.class)
    public RetMap handleException(DataIntegrityViolationException e) {
        logger.error("操作数据库出现异常:", e);
        return new RetMap("0", "操作数据库出现异常");
    }


    /**
     * 判断错误是否是已定义的已知错误，不是则由未知错误代替，同时记录在log中
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public static Result exceptionGet(Exception e) {
        if (e instanceof DescribeException) {
            DescribeException MyException = (DescribeException) e;
            return ResultUtil.error(MyException.getCode(), MyException.getMessage());
        }

        logger.error("未知异常，错误信息为：", e);
        return ResultUtil.exceptionError(ExceptionEnum.UNKNOW_ERROR);
    }
}

